# -*- coding: utf-8 -*-
#
#	Copyright (C) 2012 by Igor E. Novikov
#	
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

import gtk

from uc2 import uc2const

from sword.dialogs import msg_dialog

def get_chunks_by_identifier(parent, identifier):
	result = []
	for child in parent.childs:
		if child.identifier == identifier:
			result.append(child)
		elif child.childs:
			objs = get_chunks_by_identifier(child, identifier)
			if objs:
				result += objs
	return result

def get_chunks_by_tag(parent, tag):
	result = []
	for child in parent.childs:
		if child.chunk_tag == tag:
			result.append(child)
		if child.childs:
			objs = get_chunks_by_tag(child, tag)
			if objs:
				result += objs
	return result

def get_prop_list(objs, prop):
	result = []
	for obj in objs:
		if obj.__dict__.has_key(prop):
			result.append(obj.__dict__[prop])
	return result

def print_list(name, list):
		result = ''
		result += '\n\n' + name
		for item in list:
			result += '\n' + item
		return result

def check_doc(app, mw, doc, model_cid):
	if doc is None:
		msg = 'There is no opened document!'
		sec = 'Load "%s" document and try again.' % (uc2const.FORMAT_DESCRIPTION[model_cid])
		msg_dialog(mw, app.appdata.app_name, msg, sec)
		return False
	if not doc.doc_presenter.cid == model_cid:
		msg = 'Current document is not valid!'
		sec = 'Load "%s" document and try again.' % (uc2const.FORMAT_DESCRIPTION[model_cid])
		msg_dialog(mw, app.appdata.app_name, msg, sec)
		return False
	else:
		return True

def run_script(app, mw):
	doc = app.current_doc
	if check_doc(app, mw, doc, uc2const.CDR):
		model = doc.doc_presenter.model
		fills = get_prop_list(get_chunks_by_identifier(model, 'fild'), 'fill_id')
		outls = get_prop_list(get_chunks_by_identifier(model, 'outl'), 'stroke_id')
		fills.sort()
		outls.sort()
		objs = get_chunks_by_tag(model, 'obj ')
		objs_fills = get_prop_list(objs, 'fill_id')
		objs_outls = get_prop_list(objs, 'outl_id')
		objs_fills.sort()
		objs_outls.sort()

		res = ''
		res += print_list('Fill props', fills)
		res += print_list('Outl props', outls)
		res += print_list('Fill props used in objs', objs_fills)
		res += print_list('Outl props used in objs', objs_outls)

		msg = 'The model tree has been processed!'
		sec = 'You can find the result in details'
		msg_dialog(mw, app.appdata.app_name, msg, seconary_text=sec,
				 details=res, dlg_type=gtk.MESSAGE_INFO)



